package com.Order;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.Result.BaseRespones;
import com.Result.StatusCode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class WashinngState {
	/**
	 * @api{Post} /Order?method=WashOver 提前洗衣结束
	 * @apiName WashOver
	 * @apiGroup Order
	 * @apiDescription 学生提前结束洗衣
	 *  
	 * @apiParamExample {json} 提前结束请求样例
	 * {
	 * "StuID":1004,
	 * "OrderID":10006
	 * }
	 * 
	 * 
	 * @apiSuccessExample {json} 返回样例
	 * {
	 * 'code':5080,
	 * 'msg':'洗衣完成',
	 * 'timestamp':'2019-05-22 14:16:13'
	 * }
	 */
	public String FinishEarly(String requestString) throws IOException {
		String resource = "mybatisConfig.xml";
		InputStream is = org.apache.ibatis.io.Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sessionFactory.openSession();
		// 返回对象声明
		BaseRespones response = null;
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
		
		Order order=null;
		try {
			order=gson.fromJson(requestString, Order.class);
		} catch (Exception e) {
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}
		if (order==null) {
			response = new BaseRespones(StatusCode.jsonDeserializeFail);
			return gson.toJson(response);
		}
		order.setOrderStatus(3);
		order.setFinishedTime(new Timestamp(new Date().getTime()));
		
		OrderMapper orderMapper=session.getMapper(OrderMapper.class);
		int rs=orderMapper.washerOver(order);
		if(rs!=1) {
			List<Order> orders=orderMapper.getOrders(order);
			if (orders.isEmpty()) {
				response =new BaseRespones(StatusCode.finishedFailStatus);
			}
			else {
				response =new BaseRespones(StatusCode.finishedFailStatus);
			}
		}else {
				session.commit();
				response=new BaseRespones(StatusCode.finishedSuccess);
			}
		session.close();
		return gson.toJson(response);
	}


}
